package com.payment.controller;

import javax.servlet.http.HttpSession;

import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.member.dao.MemberDao;
import com.member.domain.MemberCommand;
import com.payment.validator.PaymentValidator;
import com.payment.dao.PaymentDao;
import com.payment.domain.PaymentCommand;

@Controller
public class PaymentWriteController {
	
	
	@Autowired
	private PaymentDao paymentDao;
	
	@Autowired
	private MemberDao memberDao;
	
	public void setPaymentDao(PaymentDao paymentDao) {
		this.paymentDao = paymentDao;
	}
	
	@ModelAttribute("paymentCommand")
	public PaymentCommand initCommand(){
		return new PaymentCommand();
	}
	
	
	@RequestMapping(value="/member/paymentWrite.do",method=RequestMethod.GET)
	public ModelAndView form(HttpSession session) {
		String id = (String)session.getAttribute("id");
		MemberCommand memberCommand = memberDao.getMember(id);
		ModelAndView mav = new ModelAndView();
		mav.addObject("memberCommand",memberCommand);
		mav.addObject("id",id);
		mav.setViewName("member_paymentWrite");
		return mav;
	}	
	
	@RequestMapping(value="/member/paymentWrite.do",method=RequestMethod.POST)
	public String submit(@ModelAttribute("payMemtCommand")PaymentCommand paymentCommand,
							BindingResult result){
				
		new PaymentValidator().validate(paymentCommand, result);
		
		if(result.hasErrors()){
			return "redirect:paymentList.do";
		}
		String phone = paymentCommand.getPhone1() + paymentCommand.getPhone2() + paymentCommand.getPhone3();
		paymentCommand.setPhone(phone);
		paymentCommand.setState(0);
		paymentDao.insertPayment(paymentCommand);
		return "redirect:paymentList.do";
	}
}

